import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import classnames from 'classnames';
import Skeleton from 'taro-skeleton'
import {View, Text} from '@tarojs/components';
import {AtIcon, AtTabs} from 'taro-ui';
import {
  FETCH_SECKILL_DETAIL,
  FETCH_SECKILL_LUCKY,
  ADD_SHARE_VOLUME,
  TARO_ENV
} from '../../constants/api';
import {getPoster} from '../../utils/poster.service'
import {user} from '../../utils/user.service';
import DetailHeader from '../components/detail-header/detail-header';
import SeckillName from './components/seckill-name';
import {http} from '../../utils/http';
import {newHttp} from "../../utils/request";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {h5Wx} from "../../utils/h5.service";
import '../scenic/detail.scss';
import './detail.scss';
import '../components/detail-bar/detail-bar.scss';

const NOT_LX_H5 = process.env.P_ENV === 'lx' && TARO_ENV !== "h5";
const IS_LX_H5 = process.env.P_ENV === 'lx' && TARO_ENV === "h5";

type PageOwnProps = {}
type PageState = {
    pkeys: any
    showLoading: boolean
    height: number
    itemId: string
    goodSeckillId: any
    good: any
    tabs: { title: string; name: 'notice' | 'desp' }[]
    oneMinute: boolean
    seckillStatus: boolean
    isLogin: boolean
    searchBarTop: any
    tabIndex: number
    currentIndex: number
    currentFlag: boolean
    notices: string
    description: string
    force_platform_seller: any
    orderNum: string
    sitePhone: string
    siteServiceWx: string
}
type IProps = PageOwnProps

interface SeckillDetail {
    props: IProps
}

class SeckillDetail extends Component {
    descIndex = 0
    noticeIndex = 0
    topHeight = 0

    state: PageState = {
        pkeys: '',
        showLoading: true,
        height: 550,
        itemId: '',
        goodSeckillId: "",
        good: null,
        tabs: [{
            title: '须知',
            name: 'notice'
        }, {
            title: '介绍',
            name: 'desp'
        }],
        oneMinute: false,
        seckillStatus: false,
        isLogin: false,
        searchBarTop: 0,
        tabIndex: 0,
        currentIndex: 0,
        currentFlag: false,
        notices: '',
        description: '',
        force_platform_seller: "",
        orderNum: '',
        sitePhone: '',
        siteServiceWx: '',
    }


    async UNSAFE_componentWillMount() {
        const isLogin = await user.checkLogin();
        // 想看就要登录
        !isLogin && user.jumpLogin(2);

        const {
            itemId = '',
            seckill_id = '',
            pkeys = '',
            force_platform_seller = '',
            orderNum = '',
            mpkey = ''
        } = Taro.getCurrentInstance().router.params

        this.setState({
            isLogin,
            itemId,
            goodSeckillId: seckill_id,
            orderNum,
            force_platform_seller
        }, () => {
          isLogin && this.getDetailData(itemId, seckill_id);
        })
    }

    async componentWillUnmount() {}

    async componentDidShow() {
        const isLogin = await user.checkLogin();
        const { itemId, goodSeckillId } = this.state;

        await Taro.setNavigationBarTitle({
            title: '限时秒杀'
        })
        if (TARO_ENV === 'h5') {
            await h5Wx.getConfig()
        }
        isLogin && this.getDetailData(itemId, goodSeckillId);
    }

    onPageScroll() {
        const {good, currentIndex, currentFlag} = this.state;
        const {descIndex, noticeIndex, topHeight} = this;
        const query = Taro.createSelectorQuery();

        query.select('#notice').boundingClientRect();
        query.select('#description').boundingClientRect();

        let index = 0;
        query.exec(res => {
            if (res[noticeIndex] && res[noticeIndex].top < topHeight) { // 购买须知
                index = noticeIndex
            }
            if (res[descIndex] && res[descIndex].top < topHeight) { // 图文介绍
                index = descIndex
            }

            if (index !== currentIndex && currentFlag) {
                this.setState({tabIndex: currentIndex});
            } else {
                this.setState({tabIndex: index});
            }
        })
    }

    async getDetailData(id = '', seckill_id = '') {
        if (id) {
            const data = {goods_id: id, seckill_id: seckill_id || this.state.goodSeckillId}
            const detail = await newHttp.catchPost(FETCH_SECKILL_DETAIL, data);

            if (detail) {
                const good = detail
                const {seckill_user_notice: notice, seckill_detail_intro: description} = detail
                good['notice'] = ""
                good['description'] = ""

                if (detail.images && detail.images.length > 0) {
                    try {
                        await Taro.getImageInfo({
                            src: detail.images[0].url + "?x-oss-process=image/resize,w_750",
                            success: (res) => {
                                const b = 750 / res.width
                                this.setState({height: res.height * b})
                            }
                        })
                    } catch (e) {}
                }
                this.setState({
                    good,
                    showLoading: false
                }, () => {
                    this.initData(detail, notice, description)
                })
            } else {
                setTimeout(() => {
                    Taro.switchTab({url: '/pages/index/index'})
                }, 2000)
                return false
            }
        } else {
            return false
        }
    }

    async initData(detail, notices = '', description = '') {
        const tabs = this.state.tabs;
        if (detail.share_data_flag) {
            this.setState({
                sloganList: detail.share_data_json.shareInfoArr ? detail.share_data_json.shareInfoArr.slogan_list : [],
                power: detail.share_data_flag,
                userPower: detail.share_data_json.power,
                shareSetting: detail.share_data_json.shareInfoArr ? detail.share_data_json.shareInfoArr.img_list : []
            })
        }

        for (let i = 0; i < tabs.length; i++) {
            if (tabs[i].name === 'desp') {
                this.descIndex = i
            }
            if (tabs[i].name === 'notice') {
                this.noticeIndex = i
            }
        }
        this.topHeight = TARO_ENV === 'h5' ? 56 : 142
        this.setState({ tabs, notices, description });
    }

    tabsClick(value = 0) {
        const tabs = this.state.tabs;
        const select = tabs[value];
        this.setState({currentIndex: value, currentFlag: true});
        const timer = setTimeout(() => {
            clearTimeout(timer);
            this.setState({currentFlag: false});
        }, 1000);
        if (process.env.TARO_ENV === 'weapp') {
            const query = Taro.createSelectorQuery();
            query.selectViewport().scrollOffset();

            switch (select.name) {
                case 'notice':
                    query.select('#notice').boundingClientRect();
                    break;
                case 'desp':
                    query.select('#description').boundingClientRect();
                    break;
                case 'evaluation':
                    query.select('#evaluation').boundingClientRect();
                    break;
                default:
                    break;
            }
            query.exec(res => {
                Taro.pageScrollTo({
                    duration: 300,
                    scrollTop: res[0].scrollTop + res[1].top - (process.env.TARO_ENV === 'tt' ? 50 : 141)
                })
            })
        } else {
            const a = document.getElementsByClassName('ScrollTo')
            if (a[value]) {
                Taro.pageScrollTo({
                    duration: 300,
                    scrollTop: a[value].offsetTop - 54
                })
            }
        }
    }

    getParams() {
        return `force_platform_seller=${this.state.force_platform_seller}&`
    }

    checkJump() {
        if (this.state.pkeys) {
            Taro.showToast({title: 'pc端此功能只做模拟，具体请前往移动端体验！', duration: 3500, icon: 'none'})
            return false
        }
        return true
    }

    onGetPoster = async () => {
        const { itemId, goodSeckillId, pkeys, isLogin } = this.state;
        /*if (!isLogin) {
            user.jumpLogin()
        }*/
        let link = `/common/seckill/detail?itemId=${itemId}&seckill_id=${goodSeckillId}`;
        if (process.env.TARO_ENV === 'h5') {
            link = window.location.origin + link;
        }
        Taro.showLoading({title: '获取海报中...'});
        const poster = await getPoster('seckillDetail', itemId, goodSeckillId, "")
        // const poster = await getPoster(FETCH_SECKILL_POSTER, {path: link, id: goodSeckillId});
        if (poster) {
            if (!pkeys) {
                http.get(ADD_SHARE_VOLUME, {category: 0, uuid: itemId})
            }
            Taro.navigateTo({url: '/distributor/poster/poster?url=' + poster.url})
        } else {
            Taro.showToast({title: '获取海报失败！', icon: 'none'})
        }
        Taro.hideLoading();
    }
    onGotoBuy = async () => {
        if (this.checkJump()) {
            const {isLogin, itemId, goodSeckillId, good, orderNum} = this.state;
            if (!isLogin) {
                user.jumpLogin()
            }
            const data = {goods_id: itemId, seckill_id: goodSeckillId};
            const result = await newHttp.catchPost(FETCH_SECKILL_LUCKY, data);
            if(result === "幸运儿") {
                const gooddata = {}
                gooddata['img'] = good.images[0].url
                gooddata['name'] = good.name
                gooddata['price'] = good.price
                gooddata['images'] = good.images
                Taro.setStorage({
                    key: "placeOrder",
                    data: JSON.stringify(gooddata),
                    success: async () => {
                        Taro.navigateTo({
                            url: `/main/order/confirm?${this.getParams()}itemId=${good.id}&fromOrderNum=${orderNum}&goods_seckill_id=${goodSeckillId}&pageType=limitedSeckill`
                        })
                    }
                })
            }
        }
    }
    onGotoHome = () => {
        if (this.checkJump()) {
            if (TARO_ENV === 'h5') {
                let mpkey = ''
                const uInfo = Taro.getStorageSync('user') || ''
                if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
                    mpkey = uInfo.mpkey
                }
                window.location.replace(window.location.origin + '/pages/index/index?mpkey=' + mpkey)
            } else {
                Taro.switchTab({url: '/pages/index/index'})
            }
        }
    }
    onContact =() => {
        const { isLogin, sitePhone, siteServiceWx } = this.state;
        if (!isLogin) {
            return user.jumpLogin()
        }
        Taro.navigateTo({url: `/distributor/contact/contact${sitePhone ? '?phone=' + sitePhone + (siteServiceWx ? '&weixin=' + siteServiceWx : '') : (siteServiceWx ? '?weixin=' + siteServiceWx : '')}`})
    }

    inOneMinute = (flag) => {
        this.setState({
            oneMinute: true,
            seckillStatus: flag
        })
    }

    render() {
        const {
            pkeys,
            height,
            showLoading,
            goodSeckillId,
            good,
            seckillStatus,
            tabIndex,
            searchBarTop,
            tabs,
            notices,
            description
        } = this.state;

        return (
            <View className='seckillDetailRoot prodRoot'>
                <GzhAuth fromWhere='seckillDetail' />
                <Skeleton
                  loading={showLoading}
                  title
                  titleWidth='100%' rowHeight='120px'
                >
                    <View className='swiper-box-wrapper'>
                    {
                        good &&
                        <View className='swiper-box'>
                            <DetailHeader
                              pkeys={pkeys}
                              height={height}
                              imagesList={(good && good.images.map(item => item.url)) || []}
                            />
                        </View>
                    }
                    </View>
                </Skeleton>

                <Skeleton
                  loading={showLoading}
                  title
                  titleWidth='100%' rowHeight='90px'
                >
                {
                    good &&
                    <View className='limit-header-raduis'>
                        <SeckillName
                          market_price={good.market_price}
                          name={good.name || ''}
                          loading={showLoading}
                          subTitle={good.seckil_short_name || ""}
                          time={good && good.status === "即将开始" ? (good.begin_date_num || 0) : (good.end_date_num || 0)}
                          goodStatus={good.status}
                          seckillStatus={seckillStatus}
                          price={good.seckill_price}
                          startDate={good.begin_date}
                          endDate={good.end_date}
                          ticketWayStr={good.ticketWayStr}
                          effective_begin_show={good.effective_begin_show}
                          effective_end_show={good.effective_end_show}
                          seckill_stock={good.surplus_inventory}
                          inOneMinute={this.inOneMinute}
                          type='limitedSecKill'
                        />
                    </View>
                }
                </Skeleton>
                <View className='good-info-box'></View>
                <Skeleton
                  loading={showLoading}
                  title
                  titleWidth='100%' rowHeight='60px'
                >
                    <View>
                        <View className='tabs' style={`${TARO_ENV !== 'h5' && `top: ${searchBarTop}Px;`}`}>
                            <View className='fixedTabs'>
                                <AtTabs current={tabIndex} tabList={tabs} onClick={this.tabsClick.bind(this)} />
                            </View>
                        </View>

                        <View className='detail-content ScrollTo no-top'>
                            <View className='rich-content' id='notice'>
                                <View className='content-header'>
                                    <View className='line' style={`background-color: ${process.env.mainColor}`} />
                                    <View className='title'>购买须知</View>
                                </View>
                                {
                                    TARO_ENV === 'weapp' &&
                                    <View className='content-info'>
                                        <parser selectable html={notices || ''} />
                                    </View>
                                }
                                {
                                    TARO_ENV === 'h5' &&
                                    <Text style='display: inline-block;' selectable className='content-info'>
                                        {!!notices && <View id='html-notice' dangerouslySetInnerHTML={{__html: notices}} />}
                                    </Text>
                                }
                            </View>
                        </View>
                        <View className='detail-content ScrollTo'>
                            <View className='rich-content' id='description'>
                                <View className='content-header'>
                                    <View className='line' style={`background-color: ${process.env.mainColor}`} />
                                    <View className='title'>图文介绍</View>
                                </View>
                                {
                                    TARO_ENV === 'weapp' &&
                                    <View className='content-info'>
                                        <parser selectable html={description || ''} />
                                    </View>
                                }
                                {
                                    TARO_ENV === 'h5' &&
                                    <Text style='display: inline-block;' selectable className='content-info'>
                                        {!!description && <View id='html-notice' dangerouslySetInnerHTML={{__html: description}} />}
                                    </Text>
                                }
                            </View>
                        </View>
                    </View>
                </Skeleton>
                <View style={{height: "70px"}} />

                {
                    good &&
                    <View className='detailBar zindex limit-detailBar'>
                        <View className='service-box'>
                            <View className='service-item goto-home' onClick={this.onGotoHome}>
                                <View className='home'><AtIcon value='icon icon-shouye-01' size='20' color='#000' /></View>
                                <View className='text'>首页</View>
                            </View>
                            {/*<View className='service-item goto-service' onClick={this.onContact}>
                                <View className='kefu'><AtIcon value='icon icon-kefu-01' size='20' color='#000' /></View>
                                <View className='text'>客服</View>
                            </View>*/}
                        </View>
                        <View className='right-btn-box'>
                            <View className='capsules'>
                                {
                                    (process.env.P_ENV !== 'lx' || NOT_LX_H5) &&
                                    <View className='get-poster-btn share' onClick={this.onGetPoster}>
                                        <View className='top'>分享</View>
                                    </View>
                                }
                                {
                                    good ?
                                    (seckillStatus || (good && good.status === "活动进行中")) ?
                                        <View className={classnames("limited", {
                                          ['limited-single']: IS_LX_H5
                                        })} onClick={this.onGotoBuy}
                                        >
                                            <View className='top'>抢购</View>
                                        </View>
                                        :
                                        good && good.status === "即将开始" ?
                                        <View className={classnames("limited", {
                                          ['limited-single']: IS_LX_H5
                                        })} style={{backgroundColor: "#FFBFAA"}}
                                        >
                                            <View className='top'>即将开始</View>
                                        </View>
                                        :
                                        <View className={classnames("limited", {
                                          ['limited-single']: IS_LX_H5
                                        })} style={{backgroundColor: "#FFBFAA"}}
                                        >
                                            <View className='top'>已售罄</View>
                                        </View>
                                    :
                                    <View className='limited' style={{backgroundColor: "#FFBFAA"}}>
                                        <View className='top'></View>
                                    </View>
                                }
                            </View>
                        </View>
                    </View>
                }
            </View>
        )
    }
}

export default SeckillDetail as ComponentClass<PageOwnProps, PageState>;
